package com.wang.util;

import org.joda.time.DateTime;

/**
 * 计数器法限流
 * Created by wang on 2017/5/3.
 */
public class SingleCounter {
    //访问计数
    public static int requestPerSecondCounter;
    //时间段基数  以当前一分钟为基准
    private static long baseMinute;

    //检查当前时间段是否超过访问限制次数
    public static boolean doCheck() {
        //检查是否在当前时间段内
        long currentMinute = DateTime.now().getMinuteOfHour();
        if (currentMinute != baseMinute) {
            setBaseTime();
            clear();
        }
        if (requestPerSecondCounter < 100) {
            requestPerSecondCounter++;
            return true;
        } else {
            return false;
        }
    }


    private static void setBaseTime() {
        baseMinute = DateTime.now().getMinuteOfHour();
    }

    private static void clear() {
        requestPerSecondCounter = 0;
    }
}
